package com.example.demo.quartz.job;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.List;
import java.util.concurrent.ExecutorService;

import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.core.env.Environment;

import com.example.demo.entity.server.ServerListenEntity;
import com.example.demo.server.dao.ServerListenDao;
import com.example.demo.thread.server.ListenServerThread;
import com.example.demo.util.EmptyUtil;
import com.example.demo.util.SpringContextUtil;
import com.example.demo.util.ThreadPoolUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ServerListenJob implements Job,Serializable  {
	private static final long serialVersionUID = 1L;
	
	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
        JobDetail jobDetail = arg0.getJobDetail();
        JobDataMap dataMap = jobDetail.getJobDataMap();
        /**
         * 获取任务中保存的方法名字，动态调用方法
         */
        String methodName = dataMap.getString("jobMethodName");
        try {
        	ServerListenJob job = new ServerListenJob();
            Method method = job.getClass().getMethod(methodName);
            method.invoke(job);
        } catch (Exception e) {
            log.error("执行服务监听任务失败",e);
        }
	}

	/**
	 * 监听服务
	 */
	public void requesToServer() {
		log.debug("开始监听各个服务状态");
		
		ServerListenDao serverListenDao = SpringContextUtil.getBean(ServerListenDao.class);
		Environment environment = SpringContextUtil.getBean(Environment.class);
		String netRegion = environment.getProperty("netRegion");//获取网络域
		
		ServerListenEntity serverParam = new ServerListenEntity();
		
		serverParam.setNet_region(netRegion);
		
		List<ServerListenEntity> listenServers = null;
		
		try {
			listenServers = serverListenDao.queryListenedServer(serverParam);
		} catch (Exception e) {
			log.error("获取被监听的服务失败",e);
			return;
		}
		
		if(EmptyUtil.isEmpty(listenServers)) {
			log.warn("没有需要监听的服务");
			return;
		}
		
		
		ExecutorService threadPool = ThreadPoolUtil.getThreadPool();
		
		int serverNum = listenServers.size();
		
		for (int i = 0; i < serverNum; i++) {
			ServerListenEntity server = listenServers.get(i);
			
			threadPool.execute(new ListenServerThread(server, serverListenDao));
		}
	}
}
